<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\OnlineExhibition;
use App\Models\Author as AuthorModel;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;

class OnlineExhibitionController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new OnlineExhibition(), function (Grid $grid) {
            $grid->column('id')->sortable();
            $grid->column('name');
            $grid->column('order_number')->editable()->sortable();
            $grid->column('created_at')->sortable();
            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('id');
            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new OnlineExhibition(['authors']), function (Show $show) {
            $show->field('id');
            $show->img()->image();
            $show->field('name');
            $show->field('order_number');
            $show->sy_content()->unescape();
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new OnlineExhibition(['authors']), function (Form $form) {
            $form->display('id');
            $form->text('name')->required();
            $form->image('img')->chunked()->uniqueName()->autoUpload()->required();
            $form->number('order_number');
            $form->tree('authors', "作家")
                ->nodes(function () {
                    return (new AuthorModel())->allNodes();
                })
                ->customFormat(function ($v) {
                    if (!$v) return [];

                    // 这一步非常重要，需要把数据库中查出来的二维数组转化成一维数组
                    return array_column($v, 'id');
                });
            $form->editor('sy_content')->rules("required", [
                "required" => "首页内容必须"
            ]);
            $form->display('created_at');
            $form->display('updated_at');
        });
    }
}
